import React, { memo, useState } from "react";
import { Button, Divider, message, Modal, Popconfirm, Table } from "antd";
import request from "@pkgs/request";
import api from "@common/api";

type Props = {
  nodeId: number;
  nodePath?: string;
  keyword: number;
  collectType: string;
};

const columns = [
  {
    title: "机器名",
    dataIndex: "name",
  },
];

const ExecuteModel: React.FC<Props> = (props) => {

  const [visible, setVisible] = useState(false);
  const [data, setData] = useState()
  const [loading, setLoading] = useState(false);
  const [tableloading, setTableLoading] = useState(false);
  const [condition, setCondition] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedData, setSelectedData] = useState<string[]>([]);

  const { keyword, nodeId, collectType } = props;

  const getTable = () => {
    setTableLoading(true);
    request(`${api.node}/${nodeId}/resources?limit=5000`)
    .then(res => {
      const { list } = res;
      setData(list)
      setTableLoading(false)
    })
  }

  const showModal = () => {
    getTable()
    setVisible(true);
  };

  const handleOk = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    setCondition(false);
    setVisible(false);
  };

  const handleCancel = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    setCondition(false);
    setVisible(false);
  };

  const issued = () => {
    const data = {
      'id': keyword,
      'hosts': selectedData
    }
    request(`${api.env}/${collectType}/run`, {method: 'POST', body: JSON.stringify(data)})
    .then(res => {
      message.success('请求成功，结果请在监控看图->环境总览下查看')
    })
    .catch(err => {
      message.error('执行失败');
    })
  }

  /**
   * @func 提交
   */
  const start = () => {
    setLoading(true);
    issued()
    setSelectedRowKeys([])
    setLoading(false);
  }

  const onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
    const selectData: string[] = [];
    selectedRows.map((item: { name: string; })=> {
      selectData.push(item.name);
    })
    setSelectedData(selectData);
    setSelectedRowKeys(selectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  function confirm() {
    setCondition(false);
    start()
  }
  
  function cancel(e: any) {
    console.log(e);
    setCondition(false);
    message.error('Click on No');
  }

  const hasSelected = selectedRowKeys.length > 0;

  return (
    <>
      <a onClick={showModal}>执行</a>
      <Modal
        title="请选择执行机器"
        footer={null}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width='50vw'
      >
        <div style={{ marginBottom: 16 }}>
        <Popconfirm
          title="是否确定下发任务?"
          onConfirm={confirm}
          onCancel={cancel}
          visible={hasSelected && condition}
          okText="Yes"
          cancelText="No"
        >
          <Button
            type="primary"
            onClick={() => {hasSelected ? setCondition(true) : setCondition(false)}}
            disabled={!hasSelected}
            loading={loading}
          >
            执行
          </Button>
          </Popconfirm>
          <span style={{ marginLeft: 8 }}>
            {hasSelected ? `选中 ${selectedRowKeys.length} 项` : ""}
          </span>
        </div>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
          pagination={{
            defaultPageSize: 50
          }}
          scroll={{ y: 240 }}
          loading={tableloading}
        />
      </Modal>
      <Divider type="vertical" />
    </>
  );
};

export default memo(ExecuteModel);
